#coding:utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
from sqlalchemy import create_engine
import tushare as ts
import pandas as pd
import time
import logging
import traceback

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='./error.log',
                    filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

#连接数据库
engine = create_engine('mysql://***')
# 重试的次数
count = 0

#大盘实时数据
def insertSMD():
    try:
        global count
        # 获取大盘数据
        ds = ts.get_today_all()
        ds['time'] = time.time()
        # 数据存入数据库
        ds.to_sql('lap_stock', engine, if_exists='append',index=False)
        time.sleep(180)
    except BaseException as e:
        if count < 10:
            count += 1
            logging.info(str("未知错误，尝试重新获取数据！"))
            # 60秒后重连
            time.sleep(60)
            return insertSMD()
        else:
            logging.error(str(e))
            logging.error(traceback.print_exc())
            logging.error(traceback.format_exc())
            logging.error(str("获取数据任务失败！"))
            count = 0
    else:
        logging.info(str("获取数据任务成功！"))
        count = 0
#弱势涨停
def insertRSZT():
    date = time.strftime("%Y-%m-%d", time.localtime())
    begin = date + " 10:00:00"
    mid = date + " 13:00:00"
    end = date + " 16:00:00"
    aStamp = int(time.mktime(time.strptime(begin, "%Y-%m-%d %H:%M:%S")))
    bStamp = int(time.mktime(time.strptime(mid, "%Y-%m-%d %H:%M:%S")))
    cStamp = int(time.mktime(time.strptime(end, "%Y-%m-%d %H:%M:%S")))

    sql_am = "SELECT code,name FROM lap_stock WHERE TIME BETWEEN " + str(aStamp) + " AND " + str(
        bStamp) + " AND changepercent < 9"
    sql_pm = "SELECT code,name FROM lap_stock WHERE TIME BETWEEN " + str(bStamp) + " AND " + str(
        cStamp) + " AND changepercent BETWEEN 9.8 AND 11"
    try:
        ds_am = pd.read_sql(sql_am, engine)
        ds_pm = pd.read_sql(sql_pm, engine)
        if ds_am.empty:
            logging.info(str(ds_am))
        elif ds_pm.empty:
            logging.info(str(ds_pm))
        else:
            ds = pd.merge(ds_am, ds_pm).drop_duplicates(['code'])
            ds['time'] = date
            ds.to_sql('lap_rszt_dayone', engine, if_exists='append',index=False)
    except BaseException as e:
        logging.error(str(e))
        logging.error(traceback.print_exc())
        logging.error(traceback.format_exc())
        logging.error(str("获取数据任务失败！"))
    else:
        logging.info(str("没有异常！"))
print("------------------start----------------")
sched = BlockingScheduler()
sched.add_job(insertSMD, 'cron', day_of_week='mon-fri', hour=12, minute=35,id='AMdata')
sched.add_job(insertSMD, 'cron', day_of_week='mon-fri', hour=17, minute=28,id='PMdata')
sched.add_job(insertRSZT, 'cron', day_of_week='mon-fri', hour=17, minute=33,id='RSZTdata')
sched.start()